# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.db import models
import datetime
from colaborador.models import *
from thumbs import ImageWithThumbsField

def content_image_name(instance, filename):
    return '/'.join(['arquivos', str(instance.categoria.slugcategoria), filename])

class Categoria(models.Model):
    nome = models.CharField(max_length=30)
    slugcategoria = models.SlugField(max_length=100, blank=True, unique=True)
    descricao = models.TextField(blank=True, null=True)
    class Meta:
        verbose_name_plural = 'Categorias'
    def __unicode__(self):
        return self.nome
    def get_absolute_url(self):
        return reverse('slainte.views.categoria', kwargs={'slugcategoria': self.slugcategoria})

class Noticia(models.Model):
    publicar = models.BooleanField(default=True)
    manchete = models.BooleanField(default=False)
    titulo = models.CharField(max_length=100, unique=True)
    subtitulo = models.CharField(max_length=200)
    chamada = models.CharField(max_length=50)
    conteudo = models.TextField()
    categoria = models.ForeignKey(Categoria)
    datapublicacao = models.DateTimeField(auto_now_add=True)
    fonte = models.CharField(max_length=20, blank=True, null=True)
    imagemDestaque = ImageWithThumbsField('Imagem Destaque',upload_to=content_image_name, sizes=((633,332),(277,180)))
    slugnoticia = models.SlugField(max_length=200, blank=True, unique=True)
    autor = models.ForeignKey(Colaborador)
    class Meta:
        verbose_name_plural = 'Notícias'
    def __unicode__(self):
        return self.titulo
    def get_absolute_url(self):
        return reverse('slainte.views.noticiainterna', kwargs={'slugnoticia': self.slugnoticia})

class DrSami(models.Model):
    publicar = models.BooleanField(default=True)
    doenca = models.CharField(max_length=100, unique=True)
    conceito = models.TextField()
    sintomas = models.TextField()
    tratamento = models.TextField()
    recomendacoes = models.TextField()
    slugdoenca = models.SlugField(max_length=100, blank=True, unique=True)
    class Meta:
        verbose_name_plural = 'Dr. Sami'
    def __unicode__(self):
        return self.doenca
    def get_absolute_url(self):
        return reverse('slainte.views.drsami', kwargs={'slugdoenca': self.slugdoenca})

class Parceiro(models.Model):
    publicar = models.BooleanField(default=True)
    destaque = models.BooleanField(default=False)
    empresa = models.CharField(max_length=100, unique=True)
    subtitulo = models.CharField(max_length=200)
    conteudo = models.TextField()
    googlemaps = models.TextField(blank=True, null=True)
    autor = models.ForeignKey(Colaborador)
    imagemDestaque = ImageWithThumbsField('Imagem Destaque',upload_to='arquivos/parceiros/', sizes=((277,180),(117,117)))
    datapublicacao = models.DateTimeField(auto_now_add=True)
    slugparceiro = models.SlugField(max_length=200, blank=True, unique=True)
    class Meta:
        verbose_name_plural = 'Parceiros'
    def __unicode__(self):
        return self.empresa
    def get_absolute_url(self):
        return reverse('slainte.views.parceiro', kwargs={'slugparceiro': self.slugparceiro})

class GaleriaVideos(models.Model):
    titulo=models.CharField('Título',max_length=100)
    url=models.CharField('Link do vídeo',max_length=200)
    data = models.DateTimeField('Data de publicação')
    slugvideo = models.SlugField(max_length=200, blank=True, unique=True)
    class Meta:
        verbose_name_plural = 'Galeria de vídeos'
    def __unicode__(self):
        return self.titulo
    def get_absolute_url(self):
        return reverse('slainte.views.video', kwargs={'slugvideo': self.slugvideo})

class Enquete(models.Model):
    questao = models.CharField(max_length=200)
    datapublicacao = models.DateTimeField('date published')
    def __unicode__(self):
        return self.questao
    def publicadohoje(self):
        return self.datapublicacao >= datetime.now() - datetime.timedelta(days=1) #

class Opcoes(models.Model):
    enquete = models.ForeignKey(Enquete)
    opcao = models.CharField(max_length=200)
    votes = models.IntegerField()
    def __unicode__(self):
        return self.opcao

### Slugs ###
from django.db.models import signals
from django.template.defaultfilters import slugify

def categoria_pre_save(signal, instance, sender, **kwargs):
    """
    Estamos gerando uma nova slug para evitar duplicidade
    """
    if not instance.slugcategoria:
        slug = slugify(instance.nome)
        novaslug = slug
        contador = 0

        while  Categoria.objects.filter(slugcategoria = novaslug).exclude(id=instance.id).count() > 0:
            contador += 1
            novaslug = '%s-%d'%(slug, contador)
        instance.slugcategoria = novaslug
signals.pre_save.connect(categoria_pre_save, sender=Categoria)

def noticia_pre_save(signal, instance, sender, **kwargs):
    """
    Estamos gerando uma nova slug para evitar duplicidade
    """
    if not instance.slugnoticia:
        slug = slugify(instance.titulo)
        novaslug = slug
        contador = 0

        while  Noticia.objects.filter(slugnoticia = novaslug).exclude(id=instance.id).count() > 0:
            contador += 1
            novaslug = '%s-%d'%(slug, contador)
        instance.slugnoticia = novaslug
signals.pre_save.connect(noticia_pre_save, sender=Noticia)

def drsami_pre_save(signal, instance, sender, **kwargs):
    instance.slugdoenca = slugify(instance.doenca)

signals.pre_save.connect(drsami_pre_save, sender=DrSami)

def video_pre_save(signal, instance, sender, **kwargs):
    instance.slugvideo = slugify(instance.titulo)

signals.pre_save.connect(video_pre_save, sender=GaleriaVideos)

def parceiro_pre_save(signal, instance, sender, **kwargs):
    instance.slugparceiro = slugify(instance.empresa)

signals.pre_save.connect(parceiro_pre_save, sender=Parceiro)